using System.Threading.Channels;
using YarpDemo.Host;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
builder.Services.AddSingleton(Channel.CreateUnbounded<TrafficContent>());
builder.Services.AddHostedService<TrafficHandlerHostedService>();

var app = builder.Build();
app.MapGet("/Ping", () => "Hello World!");
app.MapReverseProxy(proxyPipeline =>
{
    proxyPipeline.Use(async (context, next) =>
    {
        var trafficContent = new TrafficContent()
        {
            Host = context.Request.Host.ToString(),
            Method = context.Request.Method,
            Path = context.Request.Path.ToString(),
            RequestTime = DateTime.Now,
        };

        await next();
        trafficContent.StatusCode = context.Response.StatusCode;
        trafficContent.ResponseTime = DateTime.Now;

        var channel = context.RequestServices.GetService<Channel<TrafficContent>>();
        await channel!.Writer.WriteAsync(trafficContent);
    });
});
app.Run();